import os
from dataProcessor.constants import DCE_FUTURES, DCE_DATA_PATH

def rename_dce_files():
    """规范化大商所历史数据文件名称"""
    try:
        # 遍历年份文件夹
        for year in os.listdir(DCE_DATA_PATH):
            year_path = os.path.join(DCE_DATA_PATH, year)
            if not os.path.isdir(year_path):
                continue
                
            print(f"\n处理 {year} 年数据文件...")
            
            # 遍历该年份下的所有文件
            for filename in os.listdir(year_path):
                file_path = os.path.join(year_path, filename)
                if not os.path.isfile(file_path):
                    continue
                    
                # 获取文件扩展名
                name, ext = os.path.splitext(filename)
                
                # 如果文件名已经是"code_name"格式，跳过
                if '_' in name:
                    continue
                    
                # 在常量表中查找对应的合约代码
                found = False
                for code, contract_name in DCE_FUTURES.items():
                    if name == code or name == contract_name:
                        new_name = f"{code}_{contract_name}{ext}"
                        new_path = os.path.join(year_path, new_name)
                        
                        # 重命名文件
                        try:
                            os.rename(file_path, new_path)
                            print(f"已重命名: {filename} -> {new_name}")
                            found = True
                            break
                        except Exception as e:
                            print(f"重命名失败 {filename}: {str(e)}")
                
                if not found:
                    print(f"未找到对应合约信息: {filename}")
                    
        print("\n文件重命名完成！")
        
    except Exception as e:
        print(f"处理过程出错: {str(e)}")

def main():
    """主函数"""
    print("开始规范化文件名称...")
    rename_dce_files()

if __name__ == "__main__":
    main() 